import QtQuick 2.11
import QtQuick.Window 2.3
import QtQuick.Dialogs 1.2
import QtMultimedia 5.9

//import QtQuick.Controls.Material 2.2


import cn.leamus.gamedata 1.0


import "."
import _Global 1.0
import _Global.Popup 1.0
import _Global.Button 1.0
import _Global.Particles 1.0

//import GlobalJS 1.0 as GlobalJS
//import "GameJS.js" as GameJS

Window {
    id: root
    objectName: "Main"



    signal close()



    //初始化，游戏启动时由 C++ Manager 调用
    function initOnce(param) {

        //处理回调函数
        GameManager.s_GetGameDataToNetDB.connect(function(listData, type, value, code, successed, callbackFn) {
            var ret = callbackFn(listData, type, value, code, successed);
            console.debug("s_GetGameDataToNetDB return OK!", ret);
        });

        GameManager.s_SetGameDataToNetDB.connect(function(type, value, code, successed, callbackFn) {
            var ret = callbackFn(type, value, code, successed);
            console.debug("s_SetGameDataToNetDB return OK!", ret);
        });
        GameManager.s_DeleteGameDataToNetDB.connect(function(type, value, code, successed, callbackFn) {
            var ret = callbackFn(type, value, code, successed);
            console.debug("s_DeleteGameDataToNetDB return OK!", ret);
        });

        GameManager.s_InsertGameDataToNetDB.connect(function(type, value, code, successed, callbackFn) {
            var ret = callbackFn(type, value, code, successed);
            console.debug("s_InsertGameDataToNetDB return OK!", ret);
        });

        GameManager.s_UpdateGameDataToNetDB.connect(function(type, value, code, successed, callbackFn) {
            var ret = callbackFn(type, value, code, successed);
            console.debug("s_UpdateGameDataToNetDB return OK!", ret);
        });


        GameManager.s_NetDBQuery.connect(function(value, rowsAffected, lastInsertID, listData, code, successed, callbackFn) {
            var ret = callbackFn(value, rowsAffected, lastInsertID, listData, code, successed);
            console.debug("s_NetDBQuery return OK!", ret);
        });



        console.debug("userMainProject.progress", userMainProject.progress);
        userMainProject.item.initOnce(param);

    }



    //相当于全屏
    width: Screen.desktopAvailableWidth
    height: Screen.desktopAvailableHeight
    visible: true
    title: Qt.application.name + Qt.application.version
    //color: "transparent"
    color: "#00000000"
    flags: flags | Qt.FramelessWindowHint// | Qt.Widget
    //flags: Qt.SubWindow | Qt.Tool | Qt.FramelessWindowHint | Qt.WindowSystemMenuHint | Qt.WindowStaysOnTopHint
    contentOrientation: Qt.PrimaryOrientation
                        //Qt.PrimaryOrientation   //使用显示设备的首选方向。
                        //Qt.LandscapeOrientation，横屏。
                        //Qt.PortraitOrientation，竖屏。
                        //Qt.InvertedLandscapeOrientation，相对于横屏模式，旋转了180°。
                        //Qt.InvertedPortraitOrientation，相对于竖屏模式，旋转了180°。

    //Material.theme: Material.Light
    //Material.accent: Material.Light


    // 这里检测到应用处于非活跃状态时候，可以触发一个类似支付宝的解锁界面。
    //readonly property int applicationState: Qt.application.state
    Connections {
        target: Qt.application
        onStateChanged: {
            switch(Qt.application.state){
            case Qt.ApplicationActive:
                console.debug("[main]ApplicationActive");
                Global.config.bSoundOn = true;
                break;
            case Qt.ApplicationInactive:
                console.debug("[main]ApplicationInactive");
                Global.config.bSoundOn = false;
                break;
            case Qt.ApplicationSuspended:
                console.debug("[main]ApplicationSuspended");
                Global.config.bSoundOn = false;
                break;
            case Qt.ApplicationHidden:
                console.debug("[main]ApplicationHidden");
                Global.config.bSoundOn = false;
                break;
            }
        }
    }

    //屏幕自适应方法2：等比例缩放，缺点：失真，字体不是原大小
    Item {
        id: itemScale
        visible: false
        //focus: true
        //anchors.fill: parent
        width: Global.gamePos.sizeWindow.width
        height: Global.gamePos.sizeWindow.height

        transform: [
            Rotation {  //旋转

            },

            Translate { //平移

            },

            Scale {     //缩放
                origin {
                    //x: 0.5
                    //y: 0.5
                }
                xScale:
                    root.width / Global.gamePos.sizeWindow.width
                yScale:
                    root.height / Global.gamePos.sizeWindow.height
            }

        ]
        //scale: gameWindow.width / GlobalJS.GAMEWINDOW_WIDTH
        //transformOrigin: Item.TopLeft     //旋转坐标点
    }

    //屏幕自适应方法1：动态缩放，优点：图片不失真，字体正常；缺点：需要绑定，速度较慢
    Item {
        id: itemRoot
        focus: false
        anchors.fill: parent
        //width: Global.gamePos.sizeWindow.width
        //height: Global.gamePos.sizeWindow.height

        transform: [
            Rotation {  //旋转

            },

            Translate { //平移

            },

            Scale {     //缩放
                origin {
                    //x: 0.5
                    //y: 0.5
                }
                //对X、Y轴进行缩放，以适应全屏幕
//                xScale:
//                    root.width / Global.gamePos.sizeWindow.width
//                yScale:
//                    root.height / Global.gamePos.sizeWindow.height
            }

        ]

        //LOGO
        Loader {
            id: logo
            source: "Logo.qml"
            anchors.fill: parent
            z: 10000
        }


        Loader {
            id: userMainProject
            source: {
                if(Qt.platform.os !== "android")
                    return "file:" + GameManager.externalDataPath + "/QML/Game/game.qml"
                else
                    return "file:" + Platform.writableLocation(PlatformClass.DocumentsLocation) + "/QML Projects/Projects/Pets/Game/game.qml"
            }
            anchors.fill: parent
            visible: true
            focus: true
            z: 9999

            Connections {
                target: userMainProject.item

                /*onClose: {
                    console.debug("!!!!!!!!!!!onclose")
                    //userMainProject.source = "";
                }
                onHide: {
                    userMainProject.visible = false;
                }*/
            }

            onLoaded: {
                //userMainProject.focus = true;
                //userMainProject.item.focus = true;
            }
        }



        Keys.onEscapePressed:  {
            console.debug("[main]main.onEscapePressed:", event.key)
            //event.accepted = false;
            //_private.exit();
        }
        Keys.onBackPressed: {
            console.debug("[main]main.onBackPressed:", event.key)
            //event.accepted = false;
        }

        Keys.onPressed:  {
            console.debug("[main]Keys.onPressed:", event.key, Qt.Key_Return, Qt.Key_Enter);
            console.debug("[main]focus:", userMainProject.focus, userMainProject.item.focus);   //true,false
            //event.accepted = false;
        }

    }



    QtObject {  //私有数据,函数,对象等
        id: _private

        function windowSizeChanged() {
            //var t1 = root.width / Global.gamePos.sizeWindow.width
            //var t2 = root.height / Global.gamePos.sizeWindow.height
            //if(t1 > t2)
            //    t1 = t2

            //itemRoot.scale = t1

            //Global.multiplierX = root.width / Global.gamePos.posWindow.x;
            //Global.multiplierY = root.height / Global.gamePos.posWindow.y;
            Global.multiplierW = root.width / Global.gamePos.sizeWindow.width;
            Global.multiplierH = root.height / Global.gamePos.sizeWindow.height;

        }

        function exit() {
            Qt.quit();
        }
    }


    onWidthChanged: {
        //console.debug(Math.floor(width * 3 / 4), height)
        //if(Math.abs(Math.floor(width * Global.gamePos.sizeWindow.height / Global.gamePos.sizeWindow.width) - height) > 1) {
        //    height = Math.floor(width * Global.gamePos.sizeWindow.height / Global.gamePos.sizeWindow.width)
            //console.debug("width change")
        //}
        _private.windowSizeChanged()
    }
    onHeightChanged: {
        //console.debug(Math.floor(height / 3 * 4), width)
        //if(Math.abs(Math.floor(height / Global.gamePos.sizeWindow.height * Global.gamePos.sizeWindow.width) - width) > 1) {
        //    width = Math.floor(height / Global.gamePos.sizeWindow.height * Global.gamePos.sizeWindow.width)
            //console.debug("height change")
        //}
        _private.windowSizeChanged()
    }

    // @disable-check M16   //去除报错下滑线,更多错误搜索 List Of JavaScript and QML Checks
    onClosing: {
        console.debug("[main]onClosing")
        //close.accepted = false;    //窗口关闭信息:false表示不接受
        //_private.exit();
        //_private.showExitBox();
    }


    Component.onCompleted: {

        if(Global.config.bFullScreen)
            root.showFullScreen();
        else
            root.showMaximized();

        Global.window = itemRoot;


        //root.debugMsg.connect(gameUI.item.debugMsg)
        //root.debugGame.connect(gameUI.item.debugGame)



        console.debug("[main]QML工作路径:", Global._FixLocalPath_R("."));
        console.debug("[main]Qt环境上下文对象:",GameManager,GameCore,UserInfo,Platform);
        console.debug("[main]运行环境:",Qt.platform.os);
        console.debug("[main]用户入口文件:", "file:" + GameManager.externalDataPath + "/QML/Game/game.qml");

        console.debug("[main]分辨率:", "width:", Screen.desktopAvailableWidth, "height:", Screen.desktopAvailableHeight);
        console.debug("[main]分辨率:", "width:", Global.gamePos.sizeWindow.width, "height:", Global.gamePos.sizeWindow.height);
        console.debug("[main]分辨率:", "width:", Global.multiplierW, "height:", Global.multiplierH);

//其他变量测试:

        //类 的 枚举
        //console.debug("PetClass._ObjType:",(PetClass._ObjType));           //undefined
        //console.debug("PetClass.Type_Button:",(PetClass.Type_Button));     //8

        //console.debug("PetClass._Flags:",(PetClass._Flags));           //undefined
        //console.debug("PetClass.Flag_Enable:",(PetClass.Flag_Enable));  //2
        //console.debug("GameCore.Game_Button_Giveup:",GameCoreGame_Button_Giveup)  //Error!

        //console.debug("NetDataType:",CommonClass.NetDataType.DataType_JSon_Info); //OK
        //console.debug("1:",CommonClass.DataType_JSon_Info); //OK
        //console.debug("6:",CommonClass.NetDataType1.DataType_JSon_Info1);      //Error:undefined
        //console.debug("2:",CommonClass.DataType_JSon_Info1); //OK
        //console.debug("GameManager.DataType_JSon_Info:",_SaveToNetDBDataType1.DataType_JSon_Info);
        //console.debug("3:",GameManagerClass.DataType_JSon_Info1); //OK
        //console.debug("4:",GameManagerClass.NetDBDataType.DataType_JSon_Info); //OK
        console.debug("5:",GameManagerClass.DataType_JSon_Info); //OK
        //console.debug("5:",GameManagerClass.NetDataType1.DataType_JSon_Info1);    //Error:
        //console.debug("GameManager.DataType_JSon_Info:",_SaveToNetDBDataType1.DataType_JSon_Info);
        //console.debug("GameManagerClass.DataType_JSon_Info:",GameManagerClass.DataType_JSon_Info1, GameManagerClass.NetDataType1.DataType_JSon_Info1);



        console.debug("GameCoreClass._GameButtonValue:",(GameCoreClass._GameButtonValue)); //undefined
        console.debug("GameCoreClass.Game_Button_Giveup:",(GameCoreClass.Game_Button_Giveup));  //2

        console.debug("GameCoreClass._GameStatus:",(GameCoreClass._GameStatus)); //undefined
        console.debug("GameCoreClass.Game_Status_Terminated:",(GameCoreClass.Game_Status_Terminated));  //3

        //console.debug("_ClientGroupStatus:",_ClientGroupStatus);   //not defined
        //console.debug("GroupStatus_Playing:",GroupStatus_Playing);   //not defined

        //对象 的 属性
        console.debug("GameCore.testList:",GameCore.testList,GameCore.testList.length); //YES!8
        console.debug("GameCore.gameStatus:",GameCore.gameStatus);   //1

        console.debug("GameCore.socketInfo.clientGroupStatus:",GameCore.socketInfo.clientGroupStatus);   //QVariant


        console.debug("Platform.compileType():",Platform.compileType()); //debug

        console.debug("Platform.writableLocation():", Platform.writableLocation(1));
        console.debug("Platform.writableLocation():", PlatformClass.DesktopLocation); //0
        console.debug("Platform.writableLocation():", PlatformClass.StandardLocation);  //undefined



        GameManager.testStaticFn();
        console.debug(GameManagerClass);
        //GameManagerClass.testStaticFn();  //Error!!!




        //root.show();
        //login.item.raise();

        //console.debug("UserInfo.client_IsLoginedGameServer",UserInfoClass.Client_IsRegisteringInfoServer)
        //console.debug("UserInfo.client_IsLoginedGameServer",UserInfoClass.Flag2)


        /*
        //与C++信号绑定
        UserInfo.s_loginSuccess.connect(function() {   //用户登录后,创建并载入level信息,并刷新

            login.visible = false
            register.visible = false
            gameClass.visible = true;
            gameClass.focus = true;

            gameClass.item.createLevels(1)
                    });
        UserInfo.s_regSuccess.connect(function() {   //用户登录后,创建并载入level信息,并刷新

            login.visible = true
            register.visible = false

            //gameClass.item.createLevels(1)
                    });

        */



        //root.minimumWidth = Screen.desktopAvailableWidth;
        //root.minimumHeight = Screen.desktopAvailableHeight;
        //root.maximumWidth = root.minimumWidth = Global.gamePos.sizeWindow.width
        //root.maximumHeight = root.minimumHeight = Global.gamePos.sizeWindow.height
        //console.debug("size:",Global)


        /*
        GameManager.sl_qml_DebugButton(2, 1);
        GameManager.sl_qml_DebugButton(2, {"h": "h"});
        GameManager.sl_qml_DebugButton(2, [{"h": "h"}]);
        GameManager.sl_qml_DebugButton(2, 1.1);
        GameManager.sl_qml_DebugButton(2, "1");
        GameManager.sl_qml_DebugButton(2, "321a456");
        GameManager.sl_qml_DebugButton(2, GameCoreClass);
        GameManager.sl_qml_DebugButton(2, root);
        */


        /*测试文件操作
        if(GameManager.sl_qml_FileExists("test.json")) {
            console.debug("test read file:", GameManager.sl_qml_ReadFile("test.json"));
            console.debug("test delete file:", GameManager.sl_qml_DeleteFile("test.json"));
        }
        else {
            console.debug("test Write file:", GameManager.sl_qml_WriteFile(JSON.stringify({obj: 123, test1: "hello"}), "test.json", 0));
        }*/



        console.debug("[main]QML组件初始化完毕");
    }
}
